import {
  Button,
  Form,
  Input,
  Modal,
  Radio,
  Select,
  Table,
  Typography,
} from "@arco-design/web-react";
import { useAtomValue } from "jotai";
import { currentRouteAtom } from "../../components/Layout";
import { css } from "@emotion/css";
import { useQuery } from "react-query";
import { useAPI } from "../../hooks/useAPI.ts";
import { useState } from "react";
import Password from "@arco-design/web-react/es/Input/password";
import { Posts, Roles } from "../../api/types/post-and-role.ts";

const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const sexArray = [
  {
    label: "男",
    value: "0",
  },
  {
    label: "女",
    value: "1",
  },
];
const options = [
  { label: "正常", value: "0" },
  { label: "停用", value: "1" },
];

export default function SystemUser() {
  const route = useAtomValue(currentRouteAtom);

  const api = useAPI();
  const [pageSize, onPageSizeChange] = useState(10);
  const [page, setPage] = useState(0);
  const [userName, setUserName] = useState("");
  const [userStatus, setUserStatus] = useState("");
  const [formRef] = Form.useForm();

  const [postArray, setPostArray] = useState<Posts[]>([]);
  const [roleArray, setRoleArray] = useState<Roles[]>([]);

  const { data: systemUserList, isLoading } = useQuery(
    ["query-system-user-list", pageSize, page, userName, userStatus],
    async () => {
      const { data } = await api.getSystemUserList({
        pageNum: page,
        pageSize,
        userName,
        status: userStatus,
      });
      return data.data;
    },
  );
  const [isModalVisible, setIsModalVisible] = useState(false);
  const handleAddUser = async () => {
    setIsModalVisible(true);
    const { data } = await api.getSystemUser();
    setPostArray(data.posts);
    setRoleArray(data.roles);
  };

  const handleFormSubmit = async () => {
    const values = await formRef.validate();
    await api.createSystemUser(values);
  };

  return (
    <div>
      <div
        className={css`
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
        `}
      >
        <Typography.Title heading={6} style={{ margin: "0 0 20px 0" }}>
          {route?.meta.title}
        </Typography.Title>
        <Button type="primary" size="small" onClick={handleAddUser}>
          添加用户
        </Button>
        <Modal
          title="添加用户"
          visible={isModalVisible}
          onCancel={() => {
            setIsModalVisible(false);
            formRef.resetFields();
          }}
          footer={[
            <Button
              key="cancel"
              onClick={() => {
                setIsModalVisible(false);
                formRef.resetFields();
              }}
            >
              取消
            </Button>,
            <Button key="confirm" type="primary" onClick={handleFormSubmit}>
              确认
            </Button>,
          ]}
        >
          <Form
            form={formRef}
            initialValues={{
              status: "0",
            }}
          >
            <Form.Item
              label="用户昵称"
              field="nickName"
              rules={[
                {
                  required: true,
                  message: "用户昵称不得为空",
                },
              ]}
            >
              <Input placeholder="请输入用户昵称" />
            </Form.Item>
            <Form.Item
              label="用户名称"
              field="username"
              rules={[
                {
                  required: true,
                  message: "用户名称不得为空",
                },
              ]}
            >
              <Input placeholder="请输入用户名称" />
            </Form.Item>
            <Form.Item
              label="用户密码"
              field="password"
              rules={[
                {
                  required: true,
                  message: "用户密码不得为空",
                },
              ]}
            >
              <Password placeholder="请输入用户密码" />
            </Form.Item>
            <Form.Item
              rules={[
                {
                  required: true,
                  validator(value, cb) {
                    const phoneNumberRegex = /^1[3-9]\d{9}$/;
                    if (!phoneNumberRegex.test(value)) {
                      return cb("请输入正确格式的电话号码");
                    }
                    return cb(null);
                  },
                },
              ]}
              label="手机号码"
              field="phonenumber"
            >
              <Input placeholder="请输入手机号码" />
            </Form.Item>
            {/*<Form.Item label="电子邮箱" field="email">*/}
            {/*  <Input type="email" placeholder="请输入电子邮箱" />*/}
            {/*</Form.Item>*/}
            <Form.Item label="岗位" field="postIds">
              <Select placeholder="请选择岗位" allowClear>
                {postArray.map((option, index) => (
                  <Option key={index} value={option.postId}>
                    {option.postName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item label="角色" field="roleIds">
              <Select placeholder="请选择角色" allowClear>
                {roleArray.map((option, index) => (
                  <Option key={index} value={option.roleId!}>
                    {option.roleName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item label="性别" field="sex">
              <Select placeholder="请选择性别" allowClear>
                {sexArray.map((option, index) => (
                  <Option key={index} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item label="状态" field="status">
              <RadioGroup defaultValue="0">
                <Radio value="0">正常</Radio>
                <Radio value="1">停用</Radio>
              </RadioGroup>
            </Form.Item>
            <Form.Item label="备注" field="remark">
              <TextArea placeholder="请输入内容" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
      <Form layout="inline" className={css``}>
        <Form.Item field="搜索" label="搜索">
          <Input
            onChange={(keyword) => setUserName(keyword)}
            placeholder="请输入用户角色"
            style={{ width: "200px" }}
          />
        </Form.Item>
        <Form.Item label="状态" wrapperCol={{ span: 14 }}>
          <Select
            onChange={(e) => setUserStatus(e)}
            placeholder="请选择"
            allowClear
            style={{ width: "200px" }}
          >
            {options.map((option, index) => (
              <Option key={index} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
      <Table
        className={css`
          margin-top: 16px;
        `}
        loading={isLoading}
        data={systemUserList?.rows}
        pagination={{
          sizeCanChange: true,
          onPageSizeChange,
          pageSize,
          current: page,
          onChange: setPage,
          total: systemUserList?.total,
        }}
        columns={[
          {
            title: "序号",
            dataIndex: "userId",
          },
          {
            title: "用户姓名",
            dataIndex: "nickName",
          },
          {
            title: "用户角色",
            dataIndex: "userName",
          },
          {
            title: "操作",
          },
        ]}
      />
    </div>
  );
}
